package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/*
* 表示交换机
* */
public class Exchange {
    // 此处使用name作为交换机的身份标识，唯一的
    private String name;
    // 交换机类型，DIRECT FANOUT TOPIC
    private ExchangeType type = ExchangeType.DIRECT;
    // 该交换机是否要持久化存储
    private boolean durable = false;
    // 如果当前交换机没有人使用，就会自动删除
    private boolean autoDelete = false;
    // arguments表示创建交换机时一些额外的参数，如何实现？
    // 为了把arguments 存到数据库中，需要把Map转化为json格式的字符串
    private Map<String,Object> arguments = new HashMap<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() {
        // 把arguments从Map转化为json格式的字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 如果转化失败，就返回一个空的json格式的字符串
        return "{}";
    }

    // 从数据库读数据之后，构造Exchange对象，会自动调用到
    public void setArguments(String argumentsJson) {
        // 把arguments从json格式的字符串转化为Map
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String,Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    // 针对arguments，在提供一组get和set方法，方便获取/设置键值对
    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }
}
